package cc.eguid.tools;

import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 工具方法抽取
 * @author eguid
 */
public class Utils {

    /**
     * 从InputStream读取所有字节
     */
    public static byte[] readAllBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[1024];
        while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }
        return buffer.toByteArray();
    }

    /**
     * 从资源路径加载ImageIcon
     */
   public static ImageIcon loadIconFromResource(String resourceUrl) {
        // 使用getResourceAsStream从JAR包中读取资源
        InputStream inputStream = Utils.class.getResourceAsStream(resourceUrl);
        if (inputStream != null) {
            try {
                // 读取字节数据
                byte[] imageData = readAllBytes(inputStream);
                // 创建ImageIcon
                ImageIcon icon = new ImageIcon(imageData);
                if (icon.getIconWidth() > 0 && icon.getIconHeight() > 0) {
                    return icon;
                }
                return icon;
            }catch (Exception e) {
                // 静默处理，继续尝试其他路径
            }finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        System.out.println("使用getResourceAsStream从JAR包中读取资源为空");
        return null;
    }

    // 添加权限检查方法
    public static boolean checkAdminPrivileges() {
        try {
            // 尝试在系统目录创建文件来检测管理员权限
            File testFile = new File(System.getenv("SystemRoot"), "temp_test.file");
            if (testFile.createNewFile()) {
                testFile.delete();
                return true;
            }
        } catch (Exception ex) {
            return false;
        }
        return false;
    }


    /**
     * 在 Java Home 目录中查找 java.exe
      */
    protected static String findJavaExeInHome(String javaHome) {
        String[] possiblePaths = {
                javaHome + "\\bin\\java.exe",
                javaHome + "\\bin\\javaw.exe",
                javaHome + "\\jre\\bin\\java.exe",
                javaHome + "\\jre\\bin\\javaw.exe"
        };

        for (String path : possiblePaths) {
            if (new File(path).exists()) {
                return path;
            }
        }
        return null;
    }

    /**
     * 在 PATH 环境变量中查找 Java
     */
    protected static List<String> findJavaInPath() {
        List<String> javaPaths = new ArrayList<>();
        String pathEnv = System.getenv("PATH");

        if (pathEnv != null) {
            String[] pathDirs = pathEnv.split(";");
            for (String dir : pathDirs) {
                if (dir.contains("Java") || dir.contains("jdk") || dir.contains("jre")) {
                    File javaExe = new File(dir, "java.exe");
                    File javawExe = new File(dir, "javaw.exe");

                    if (javaExe.exists()) {
                        javaPaths.add(javaExe.getAbsolutePath());
                    } else if (javawExe.exists()) {
                        javaPaths.add(javawExe.getAbsolutePath());
                    }
                }
            }
        }
        return javaPaths;
    }

    /**
     * 搜索常见的 Java 安装路径
     */
    protected static List<String> searchCommonJavaPaths() {
        List<String> javaPaths = new ArrayList<>();

        // 常见安装路径
        String[] commonBasePaths = {
                "C:\\Program Files\\Java",
                "C:\\Program Files (x86)\\Java",
                "D:\\Program Files\\Java",
                System.getenv("PROGRAMFILES") + "\\Java",
                System.getenv("PROGRAMFILES(X86)") + "\\Java"
        };

        for (String basePath : commonBasePaths) {
            File javaDir = new File(basePath);
            if (javaDir.exists() && javaDir.isDirectory()) {
                File[] subDirs = javaDir.listFiles();
                if (subDirs != null) {
                    for (File subDir : subDirs) {
                        if (subDir.isDirectory() &&
                                (subDir.getName().startsWith("jdk") ||
                                        subDir.getName().startsWith("jre") ||
                                        subDir.getName().matches("jdk[0-9_.]+") ||
                                        subDir.getName().matches("jre[0-9_.]+"))) {

                            String javaExePath = findJavaExeInHome(subDir.getAbsolutePath());
                            if (javaExePath != null) {
                                javaPaths.add(javaExePath);
                            }
                        }
                    }
                }
            }
        }
        return javaPaths;
    }

    // 检查服务是否已存在
    protected static boolean checkServiceExists(String serviceName) {
        try {
            Process process = Runtime.getRuntime().exec("sc query \"" + serviceName + "\"");
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "GBK"));

            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains("STATE")) {
                    return true;
                }
            }
            process.waitFor();
        } catch (Exception ex) {
            // 查询失败通常表示服务不存在
        }
        return false;
    }
}
